/**
 * Created by joy on 25/09/2017.
 */
import RandomUtil from 'js-common-modules/lib/utils/RandomUtil'
import HttpRequestUtil from 'js-common-modules/lib/utils/HttpRequestUtil'

export default class Peer {

  constructor () {
    this.peers = {
      client: {},
      server: {}
    }
  }

  async startServer (socketServerHelper, port) {
    socketServerHelper.listen(port, (clientId) => {
      peerHelper.removePeer(clientId, 'client')
      // 如果没有了邻居，则停止产块
      peerHelper.getPeersCount() === 0 && blockHelper.stopGeneBlockTimer()
    }, (clientId, { clientInfo }) => {
      peerHelper.addPeer(clientId, clientInfo, 'client')
      blockHelper.startGeneBlockTimer()
    })
    logger.info('socket已监听：', port)
  }

  _isConnectSelf (url) {
    return url === `http://${args['restHost']}:${args['syncPort']}`
  }

  async connectPeer (peer_) {
    const url = peer_['socket']
    logger.info(`连接peer ${url} 中...`)
    // 检查是否是连自己
    if (this._isConnectSelf(url)) {
      logger.warn('不可以连接自己')
      return
    }
    return socketClientHelper.connectNewServer(url, (url) => {
      peerHelper.removePeer(url, 'server')
    }, (url, { serverInfo }) => {
      logger.info(`连接peer ${url} 成功`)
      Object.assign(serverInfo, peer_)
      peerHelper.addPeer(url, serverInfo, 'server')
    })
  }

  async getChainInfo () {
    // 获取当前区块高度等信息
    // 取一随机的peer(客户端或者服务端)
    const peer = this._getRandomPeer()
    return HttpRequestUtil.getJson(peer['rest'] + '/chain/get_info')
  }

  _getRandomPeer () {
    let firstList = []
    if (Object.keys(peerHelper.peers['client']).length > 0) {
      firstList.push('client')
    }
    if (Object.keys(peerHelper.peers['server']).length > 0) {
      firstList.push('server')
    }
    const clientOrServer = RandomUtil.getRandomFromList(firstList)
    const newTarget = peerHelper.peers[clientOrServer]
    const result = newTarget[RandomUtil.getRandomFromList(Object.keys(newTarget))]
    return {
      server: clientOrServer === 'server',
      client: clientOrServer === 'client',
      ...result
    }
  }

  getPeersCount () {
    return Object.keys(this.peers['client']).length + Object.keys(this.peers['server']).length
  }

  addPeer (key, value, type) {
    this.peers[type][key] = value
  }

  removePeer (key, type) {
    delete this.peers[type][key]
  }

  // async startSyncTimer () {
  //   await this._syncData()
  //   TimeUtil.setInterval(async () => {
  //     await this._syncData()
  //   }, hardConfig['syncInterval'])
  // }
  //
  // async _syncData () {
  //   // 随机找peer取最新块高
  //   const chainInfo = await this.getChainInfo()
  //   logger.error('chainInfo', chainInfo)
  //   const localBlockHeight = await blockHelper.getLocalLatestHeight()
  //   if (chainInfo['chain']['latestHeight'] > localBlockHeight) {
  //     logger.error('可以向此节点同步', `${localBlockHeight} -> ${chainInfo['chain']['latestHeight']}`)
  //     // 每次3000条记录 TODO
  //
  //   }
  // }
}
